[[...path]].page.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. import React, { ReactNode, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import type {
  11. GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { useCurrentGrowiLayoutFluidClassName, useEditorModeClassName } from '~/client/services/layout';
  19. import { PageView } from '~/components/Page/PageView';
  20. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  21. import type { CrowiRequest } from '~/interfaces/crowi-request';
  22. import type { EditorConfig } from '~/interfaces/editor-settings';
  23. import type { IPageGrantData } from '~/interfaces/page';
  24. import type { RendererConfig } from '~/interfaces/services/renderer';
  25. import type { PageModel, PageDocument } from '~/server/models/page';
  26. import type { PageRedirectModel } from '~/server/models/page-redirect';
  27. import {
  28. useCurrentUser,
  29. useIsForbidden, useIsSharedUser,
  30. useIsEnabledStaleNotification, useIsIdenticalPath,
  31. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  32. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  33. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  34. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPathname,
  35. useIsSlackConfigured, useRendererConfig,
  36. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  37. } from '~/stores/context';
  38. import { useEditingMarkdown } from '~/stores/editor';
  39. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  40. import {
  41. useSWRxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId, useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  42. } from '~/stores/page';
  43. import { useRedirectFrom } from '~/stores/page-redirect';
  44. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  45. import { useSelectedGrant } from '~/stores/ui';
  46. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  47. import loggerFactory from '~/utils/logger';
  48. import { BasicLayout } from '../components/Layout/BasicLayout';
  49. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  50. import type { GrowiSubNavigationSwitcherProps } from '../components/Navbar/GrowiSubNavigationSwitcher';
  51. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  52. import type { NextPageWithLayout } from './_app.page';
  53. import type { CommonProps } from './utils/commons';
  54. import {
  55. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig,
  56. } from './utils/commons';
  57. declare global {
  58. // eslint-disable-next-line vars-on-top, no-var
  59. var globalEmitter: EventEmitter;
  60. }
  61. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  62. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  63. const GrowiSubNavigationSwitcher = dynamic<GrowiSubNavigationSwitcherProps>(() => import('../components/Navbar/GrowiSubNavigationSwitcher')
  64. .then(mod => mod.GrowiSubNavigationSwitcher), { ssr: false });
  65. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  66. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  67. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  68. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  69. const logger = loggerFactory('growi:pages:all');
  70. const {
  71. isPermalink: _isPermalink, isTrashPage: _isTrashPage, isCreatablePage,
  72. } = pagePathUtils;
  73. const { removeHeadingSlash } = pathUtils;
  74. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  75. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  76. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  77. {
  78. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  79. return v?.data != null
  80. && v?.data.toObject != null
  81. && v?.meta != null
  82. && isIPageInfoForEntity(v.meta);
  83. },
  84. serialize: (v) => {
  85. return {
  86. data: superjson.stringify(v.data.toObject()),
  87. meta: superjson.stringify(v.meta),
  88. };
  89. },
  90. deserialize: (v) => {
  91. return {
  92. data: superjson.parse(v.data),
  93. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  94. };
  95. },
  96. },
  97. 'IPageToShowRevisionWithMetaTransformer',
  98. );
  99. // GrowiContextualSubNavigation for NOT shared page
  100. type GrowiContextualSubNavigationProps = {
  101. isLinkSharingDisabled: boolean,
  102. }
  103. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  104. const { isLinkSharingDisabled } = props;
  105. const { data: currentPage } = useSWRxCurrentPage();
  106. return (
  107. <div data-testid="grw-contextual-sub-nav">
  108. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  109. </div>
  110. );
  111. };
  112. const PutbackPageModal = (): JSX.Element => {
  113. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  114. return <PutbackPageModal />;
  115. };
  116. type Props = CommonProps & {
  117. pageWithMeta: IPageToShowRevisionWithMeta | null,
  118. // pageUser?: any,
  119. redirectFrom?: string;
  120. // shareLinkId?: string;
  121. isLatestRevision?: boolean,
  122. isIdenticalPathPage?: boolean,
  123. isForbidden: boolean,
  124. isNotFound: boolean,
  125. isNotCreatable: boolean,
  126. // isAbleToDeleteCompletely: boolean,
  127. templateTagData?: string[],
  128. templateBodyData?: string,
  129. isSearchServiceConfigured: boolean,
  130. isSearchServiceReachable: boolean,
  131. isSearchScopeChildrenAsDefault: boolean,
  132. isSlackConfigured: boolean,
  133. // isMailerSetup: boolean,
  134. isAclEnabled: boolean,
  135. // hasSlackConfig: boolean,
  136. drawioUri: string | null,
  137. hackmdUri: string,
  138. noCdn: string,
  139. // highlightJsStyle: string,
  140. isAllReplyShown: boolean,
  141. isContainerFluid: boolean,
  142. editorConfig: EditorConfig,
  143. isEnabledStaleNotification: boolean,
  144. isEnabledAttachTitleHeader: boolean,
  145. // isEnabledLinebreaks: boolean,
  146. // isEnabledLinebreaksInComments: boolean,
  147. adminPreferredIndentSize: number,
  148. isIndentSizeForced: boolean,
  149. disableLinkSharing: boolean,
  150. grantData?: IPageGrantData,
  151. rendererConfig: RendererConfig,
  152. };
  153. const Page: NextPageWithLayout<Props> = (props: Props) => {
  154. // register global EventEmitter
  155. if (isClient() && window.globalEmitter == null) {
  156. window.globalEmitter = new EventEmitter();
  157. }
  158. const router = useRouter();
  159. useCurrentUser(props.currentUser ?? null);
  160. // commons
  161. useEditorConfig(props.editorConfig);
  162. useCsrfToken(props.csrfToken);
  163. // page
  164. useIsContainerFluid(props.isContainerFluid);
  165. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  166. useIsForbidden(props.isForbidden);
  167. useIsNotCreatable(props.isNotCreatable);
  168. useRedirectFrom(props.redirectFrom ?? null);
  169. useIsSharedUser(false); // this page cann't be routed for '/share'
  170. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  171. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  172. useIsSearchPage(false);
  173. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  174. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  175. useIsSearchServiceReachable(props.isSearchServiceReachable);
  176. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  177. useIsSlackConfigured(props.isSlackConfigured);
  178. // useIsMailerSetup(props.isMailerSetup);
  179. useIsAclEnabled(props.isAclEnabled);
  180. // useHasSlackConfig(props.hasSlackConfig);
  181. useDrawioUri(props.drawioUri);
  182. useHackmdUri(props.hackmdUri);
  183. // useNoCdn(props.noCdn);
  184. useDefaultIndentSize(props.adminPreferredIndentSize);
  185. useIsIndentSizeForced(props.isIndentSizeForced);
  186. useDisableLinkSharing(props.disableLinkSharing);
  187. useRendererConfig(props.rendererConfig);
  188. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  189. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  190. useIsAllReplyShown(props.isAllReplyShown);
  191. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  192. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  193. const { pageWithMeta } = props;
  194. const pageId = pageWithMeta?.data._id;
  195. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  196. const revisionBody = pageWithMeta?.data.revision?.body;
  197. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  198. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  199. useCurrentPathname(props.currentPathname);
  200. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  201. const { mutate: mutateIsNotFound } = useIsNotFound();
  202. const { mutate: mutateCurrentPageId } = useCurrentPageId();
  203. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  204. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  205. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  206. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  207. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  208. const { mutate: mutateRevisionIdHackmdSynced } = useRevisionIdHackmdSynced();
  209. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  210. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  211. useSetupGlobalSocket();
  212. useSetupGlobalSocketForPage(pageId);
  213. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName(pageWithMeta?.data);
  214. const shouldRenderPutbackPageModal = pageWithMeta != null
  215. ? _isTrashPage(pageWithMeta.data.path)
  216. : false;
  217. // sync grant data
  218. useEffect(() => {
  219. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  220. mutateSelectedGrant(grantDataToApply);
  221. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  222. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  223. useEffect(() => {
  224. const decodedURI = decodeURI(window.location.pathname);
  225. if (isClient() && decodedURI !== props.currentPathname) {
  226. const { search, hash } = window.location;
  227. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  228. }
  229. }, [props.currentPathname, router]);
  230. // initialize mutateEditingMarkdown only once per page
  231. // need to include useCurrentPathname not useCurrentPagePath
  232. useEffect(() => {
  233. if (props.currentPathname != null) {
  234. mutateEditingMarkdown(revisionBody);
  235. }
  236. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  237. useEffect(() => {
  238. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  239. mutateRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  240. }, [mutateRemoteRevisionId, mutateRevisionIdHackmdSynced, pageWithMeta?.data.revision?._id, pageWithMeta?.data.revisionHackmdSynced]);
  241. useEffect(() => {
  242. mutateCurrentPageId(pageId ?? null);
  243. }, [mutateCurrentPageId, pageId]);
  244. useEffect(() => {
  245. mutateIsNotFound(props.isNotFound);
  246. }, [mutateIsNotFound, props.isNotFound]);
  247. useEffect(() => {
  248. mutateIsLatestRevision(props.isLatestRevision);
  249. }, [mutateIsLatestRevision, props.isLatestRevision]);
  250. useEffect(() => {
  251. mutateTemplateTagData(props.templateTagData);
  252. }, [props.templateTagData, mutateTemplateTagData]);
  253. useEffect(() => {
  254. mutateTemplateBodyData(props.templateBodyData);
  255. }, [props.templateBodyData, mutateTemplateBodyData]);
  256. const title = generateCustomTitleForPage(props, pagePath);
  257. return (
  258. <>
  259. <Head>
  260. <title>{title}</title>
  261. </Head>
  262. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  263. <header className="py-0 position-relative">
  264. <div id="grw-subnav-container">
  265. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  266. </div>
  267. </header>
  268. <div className="d-edit-none">
  269. <GrowiSubNavigationSwitcher isLinkSharingDisabled={props.disableLinkSharing} />
  270. </div>
  271. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  272. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  273. <DisplaySwitcher
  274. pageView={
  275. <PageView
  276. pagePath={pagePath}
  277. initialPage={pageWithMeta?.data}
  278. rendererConfig={props.rendererConfig}
  279. />
  280. }
  281. />
  282. <PageStatusAlert />
  283. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  284. </div>
  285. </>
  286. );
  287. };
  288. type LayoutProps = Props & {
  289. children?: ReactNode
  290. }
  291. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  292. const className = useEditorModeClassName();
  293. // init sidebar config with UserUISettings and sidebarConfig
  294. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  295. return (
  296. <BasicLayout className={className}>
  297. {children}
  298. </BasicLayout>
  299. );
  300. };
  301. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  302. return (
  303. <>
  304. <DrawioViewerScript />
  305. <Layout {...page.props}>
  306. {page}
  307. </Layout>
  308. <UnsavedAlertDialog />
  309. <DescendantsPageListModal />
  310. <DrawioModal />
  311. <HandsontableModal />
  312. <TemplateModal />
  313. </>
  314. );
  315. };
  316. function getPageIdFromPathname(currentPathname: string): string | null {
  317. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  318. }
  319. class MultiplePagesHitsError extends ExtensibleCustomError {
  320. pagePath: string;
  321. constructor(pagePath: string) {
  322. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  323. this.pagePath = pagePath;
  324. }
  325. }
  326. // apply parent page grant fot creating page
  327. async function applyGrantToPage(props: Props, ancestor: any) {
  328. await ancestor.populate('grantedGroup');
  329. const grant = {
  330. grant: ancestor.grant,
  331. };
  332. const grantedGroup = ancestor.grantedGroup ? {
  333. grantedGroup: {
  334. id: ancestor.grantedGroup.id,
  335. name: ancestor.grantedGroup.name,
  336. },
  337. } : {};
  338. props.grantData = Object.assign(grant, grantedGroup);
  339. }
  340. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  341. const { model: mongooseModel } = await import('mongoose');
  342. const req: CrowiRequest = context.req as CrowiRequest;
  343. const { crowi } = req;
  344. const { revisionId } = req.query;
  345. const Page = crowi.model('Page') as PageModel;
  346. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  347. const { pageService } = crowi;
  348. let currentPathname = props.currentPathname;
  349. const pageId = getPageIdFromPathname(currentPathname);
  350. const isPermalink = _isPermalink(currentPathname);
  351. const { user } = req;
  352. if (!isPermalink) {
  353. // check redirects
  354. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  355. if (chains != null) {
  356. // overwrite currentPathname
  357. currentPathname = chains.end.toPath;
  358. props.currentPathname = currentPathname;
  359. // set redirectFrom
  360. props.redirectFrom = chains.start.fromPath;
  361. }
  362. // check whether the specified page path hits to multiple pages
  363. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  364. if (count > 1) {
  365. throw new MultiplePagesHitsError(currentPathname);
  366. }
  367. }
  368. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  369. const page = pageWithMeta?.data as unknown as PageDocument;
  370. // add user to seen users
  371. if (page != null && user != null) {
  372. await page.seen(user);
  373. }
  374. // populate & check if the revision is latest
  375. if (page != null) {
  376. page.initLatestRevisionField(revisionId);
  377. await page.populateDataToShowRevision();
  378. props.isLatestRevision = page.isLatestRevision();
  379. }
  380. if (page == null && user != null) {
  381. const templateData = await Page.findTemplate(props.currentPathname);
  382. if (templateData != null) {
  383. props.templateTagData = templateData.templateTags as string[];
  384. props.templateBodyData = templateData.templateBody as string;
  385. }
  386. // apply pagrent page grant
  387. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  388. if (ancestor != null) {
  389. await applyGrantToPage(props, ancestor);
  390. }
  391. }
  392. props.pageWithMeta = pageWithMeta;
  393. }
  394. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  395. const req: CrowiRequest = context.req as CrowiRequest;
  396. const { crowi } = req;
  397. const Page = crowi.model('Page') as PageModel;
  398. const { currentPathname } = props;
  399. const pageId = getPageIdFromPathname(currentPathname);
  400. const isPermalink = _isPermalink(currentPathname);
  401. const page = props.pageWithMeta?.data;
  402. if (props.isIdenticalPathPage) {
  403. props.isNotCreatable = true;
  404. }
  405. else if (page == null) {
  406. props.isNotFound = true;
  407. props.isNotCreatable = !isCreatablePage(currentPathname);
  408. // check the page is forbidden or just does not exist.
  409. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  410. props.isForbidden = count > 0;
  411. }
  412. else {
  413. props.isNotFound = page.isEmpty;
  414. props.isNotCreatable = false;
  415. props.isForbidden = false;
  416. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  417. if (isPermalink && page.isEmpty) {
  418. props.currentPathname = page.path;
  419. }
  420. // /path/to/page ==> /62a88db47fed8b2d94f30000
  421. if (!isPermalink && !page.isEmpty) {
  422. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  423. if (!isToppage) {
  424. props.currentPathname = `/${page._id}`;
  425. }
  426. }
  427. }
  428. }
  429. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  430. // const req: CrowiRequest = context.req as CrowiRequest;
  431. // const { crowi } = req;
  432. // const UserModel = crowi.model('User');
  433. // if (isUserPage(props.currentPagePath)) {
  434. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  435. // if (user != null) {
  436. // props.pageUser = JSON.stringify(user.toObject());
  437. // }
  438. // }
  439. // }
  440. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  441. const req: CrowiRequest = context.req as CrowiRequest;
  442. const { crowi } = req;
  443. const {
  444. searchService, configManager, aclService,
  445. } = crowi;
  446. props.isSearchServiceConfigured = searchService.isConfigured;
  447. props.isSearchServiceReachable = searchService.isReachable;
  448. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  449. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  450. // props.isMailerSetup = mailService.isMailerSetup;
  451. props.isAclEnabled = aclService.isAclEnabled();
  452. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  453. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  454. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  455. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  456. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  457. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  458. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  459. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  460. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  461. props.editorConfig = {
  462. upload: {
  463. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  464. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  465. },
  466. };
  467. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  468. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  469. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  470. props.rendererConfig = {
  471. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  472. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  473. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  474. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  475. plantumlUri: process.env.PLANTUML_URI ?? null,
  476. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  477. // XSS Options
  478. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  479. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  480. attrWhiteList: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  481. tagWhiteList: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  482. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  483. };
  484. }
  485. /**
  486. * for Server Side Translations
  487. * @param context
  488. * @param props
  489. * @param namespacesRequired
  490. */
  491. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  492. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  493. props._nextI18Next = nextI18NextConfig._nextI18Next;
  494. }
  495. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  496. const req = context.req as CrowiRequest<IUserHasId & any>;
  497. const { user } = req;
  498. const result = await getServerSideCommonProps(context);
  499. // check for presence
  500. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  501. if (!('props' in result)) {
  502. throw new Error('invalid getSSP result');
  503. }
  504. const props: Props = result.props as Props;
  505. if (props.redirectDestination != null) {
  506. return {
  507. redirect: {
  508. permanent: false,
  509. destination: props.redirectDestination,
  510. },
  511. };
  512. }
  513. if (user != null) {
  514. props.currentUser = user.toObject();
  515. }
  516. try {
  517. await injectPageData(context, props);
  518. }
  519. catch (err) {
  520. if (err instanceof MultiplePagesHitsError) {
  521. props.isIdenticalPathPage = true;
  522. }
  523. else {
  524. throw err;
  525. }
  526. }
  527. await injectRoutingInformation(context, props);
  528. injectServerConfigurations(context, props);
  529. await injectNextI18NextConfigurations(context, props, ['translation']);
  530. return {
  531. props,
  532. };
  533. };
  534. export default Page;